package com.project.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.demo.controller.base.BaseController;
import com.project.demo.entity.Hits;
import com.project.demo.service.HitsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 点击：(Hits)表控制层
 */
@Slf4j
@RestController
@RequestMapping("hits")
public class HitsController extends BaseController<Hits, HitsService> {
    /**
     * 服务对象
     */
    @Autowired
    public HitsController(HitsService service) {
        setService(service);
    }

    /**
     * 获取点击趋势统计数据
     * @param timeDimension 时间维度：day/week/month
     * @return
     */
    @GetMapping("trend_statistics")
    public Map<String, Object> getTrendStatistics(@RequestParam(required = false, defaultValue = "day") String timeDimension) {
        try {
            String sql;
            SimpleDateFormat sdf;
            Calendar cal = Calendar.getInstance();
            Map<String, Integer> dateMap = new LinkedHashMap<>();
            
            if ("day".equals(timeDimension)) {
                // 按日期统计，获取最近7天
                sql = "SELECT DATE_FORMAT(create_time, '%Y-%m-%d') as date, COUNT(*) as count " +
                        "FROM hits " +
                        "WHERE create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY) " +
                        "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d') " +
                        "ORDER BY date ASC";
                
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                for (int i = 6; i >= 0; i--) {
                    cal.setTime(new Date());
                    cal.add(Calendar.DAY_OF_MONTH, -i);
                    String date = sdf.format(cal.getTime());
                    dateMap.put(date, 0);
                }
            } else if ("week".equals(timeDimension)) {
                // 按周统计，获取最近6周
                sql = "SELECT CONCAT(YEAR(create_time), '-', LPAD(WEEK(create_time), 2, '0')) as week, COUNT(*) as count " +
                        "FROM hits " +
                        "WHERE create_time >= DATE_SUB(NOW(), INTERVAL 6 WEEK) " +
                        "GROUP BY YEAR(create_time), WEEK(create_time) " +
                        "ORDER BY YEAR(create_time), WEEK(create_time) ASC";
                
                sdf = new SimpleDateFormat("yyyy");
                for (int i = 5; i >= 0; i--) {
                    cal.setTime(new Date());
                    cal.add(Calendar.WEEK_OF_YEAR, -i);
                    int year = cal.get(Calendar.YEAR);
                    int week = cal.get(Calendar.WEEK_OF_YEAR);
                    String weekKey = String.format("%d-%02d", year, week);
                    dateMap.put(weekKey, 0);
                }
            } else {
                // 按月统计，获取最近6个月
                sql = "SELECT DATE_FORMAT(create_time, '%Y-%m') as month, COUNT(*) as count " +
                        "FROM hits " +
                        "WHERE create_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH) " +
                        "GROUP BY DATE_FORMAT(create_time, '%Y-%m') " +
                        "ORDER BY month ASC";
                
                sdf = new SimpleDateFormat("yyyy-MM");
                for (int i = 5; i >= 0; i--) {
                    cal.setTime(new Date());
                    cal.add(Calendar.MONTH, -i);
                    String month = sdf.format(cal.getTime());
                    dateMap.put(month, 0);
                }
            }
            
            Query query = service.runCountSql(sql);
            @SuppressWarnings("unchecked")
            List<Object[]> resultList = query.getResultList();
            
            // 填充查询结果
            for (Object[] row : resultList) {
                String dateKey = (String) row[0];
                Long count = ((Number) row[1]).longValue();
                if (dateMap.containsKey(dateKey)) {
                    dateMap.put(dateKey, count.intValue());
                }
            }
            
            // 转换为前端需要的格式
            List<Map<String, Object>> list = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : dateMap.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                item.put("date", entry.getKey());
                item.put("count", entry.getValue());
                list.add(item);
            }
            
            JSONObject result = new JSONObject();
            result.put("list", list);
            return success(result);
        } catch (Exception e) {
            log.error("获取点击趋势统计数据失败", e);
            return error(50000, "获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取点击时段分布统计数据
     * @return
     */
    @GetMapping("hour_statistics")
    public Map<String, Object> getHourStatistics() {
        try {
            // 查询24小时内的点击分布
            String sql = "SELECT HOUR(create_time) as hour, COUNT(*) as count " +
                    "FROM hits " +
                    "WHERE create_time >= DATE_SUB(NOW(), INTERVAL 7 DAY) " +
                    "GROUP BY HOUR(create_time) " +
                    "ORDER BY hour ASC";
            
            Query query = service.runCountSql(sql);
            @SuppressWarnings("unchecked")
            List<Object[]> resultList = query.getResultList();
            
            // 生成24小时数据（确保每个小时都有数据）
            Map<Integer, Integer> hourMap = new LinkedHashMap<>();
            for (int i = 0; i < 24; i++) {
                hourMap.put(i, 0);
            }
            
            // 填充查询结果
            for (Object[] row : resultList) {
                Integer hour = ((Number) row[0]).intValue();
                Long count = ((Number) row[1]).longValue();
                hourMap.put(hour, count.intValue());
            }
            
            // 转换为前端需要的格式
            List<Map<String, Object>> list = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entry : hourMap.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                item.put("hour", entry.getKey());
                item.put("count", entry.getValue());
                list.add(item);
            }
            
            JSONObject result = new JSONObject();
            result.put("list", list);
            return success(result);
        } catch (Exception e) {
            log.error("获取点击时段分布统计数据失败", e);
            return error(50000, "获取统计数据失败: " + e.getMessage());
        }
    }

}


